package com.gopay.checkorder.service.task;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.gopay.checkorder.manager.BankOrderManager;
import com.gopay.common.domain.bank.CheckOrderFailLog;

@Service("taskObserver")
public class TaskObserver implements Observer {

	private final static Logger logger = LoggerFactory.getLogger("CHECK_ORDER");
	// private static final String SWITCH_OFF= "off";
	private static final String SWITCH_ON = "on";

	@Resource(name = "smsConfig")
	private Map<String, String> smsConfig;

	@Resource(name = "bankList")
	private List<String> bankList;
	
	@Resource(name = "bankOrderManager")
    protected BankOrderManager bankOrderManager;

	@Override
	public void update(Observable o, Object arg) {

		List<String> totalList = BankCountDownLatch.getBankCountDownLatch();

		List<String> failList = BankCountDownLatch.getBankCountDownLatchFail();

		// 对单银行list
		for (String bank : bankList) {

			if (!StringUtils.isEmpty(bank)) {

				if (!totalList.isEmpty() && !failList.isEmpty()) {

					// 单个银行对单总量
					int totalCount = countBank(totalList, bank);
					// 单个银行对单失败总量
					int failCount = countBank(failList, bank);
					if (totalCount == 0) {
						continue;
					}
					if (failCount == 0) {
						continue;
					}

					// 计算失败比例
					double value = (((double)failCount) / ((double)totalCount)) * 100;
					//系统配置失败比例
					Integer scale = Integer.valueOf(smsConfig.get("scale"));
                    if (value >= scale.doubleValue()) {
                        // 对账报警对象
                        CheckOrderFailLog checkOrderFailLog = new CheckOrderFailLog();
                        checkOrderFailLog.setBankCode(bank);
                        checkOrderFailLog.setTransTime(new Date());
                        checkOrderFailLog.setCheckCount(totalCount);
                        checkOrderFailLog.setFailCount(failCount);
                        checkOrderFailLog.setFailureRate(value);
                        checkOrderFailLog.setRemark(bank + "通讯异常");

                        logger.error(bank + " CheckOrderFailLog 对账失败报警");
                        bankOrderManager.insertCheckOrderFailLog(checkOrderFailLog);
                    } else {
						continue;
					}

				} else {
					continue;
				}
			}
		}

	}

	// 计算list中每个银行对单总数或失败数的数量
	public int countBank(List<String> list, String bankName) {

		String listStr = list.toString();
		int count = listStr.length();
		if (count != 0) {
			String endStr = listStr.replace(bankName, "");
			int endCount = endStr.length();
			if (count >= endCount) {
				return (count - endCount) / bankName.length();
			} else {
				return 0;
			}
		} else {
			return 0;
		}
	}

}
